package adapter;

import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shizhefei.mvc.IDataAdapter;
import com.shizhefei.recyclerview.HFAdapter;

import java.util.ArrayList;
import java.util.List;

import widget.RecyViewHolder;

/**
 * Created by chm on 2018/4/11.
 */

public abstract class PullRecyAdpater<T> extends HFAdapter implements IDataAdapter<List<T>> {

    private List<T> mDatas = new ArrayList<>();

    private int layoutResId;

    public PullRecyAdpater(@LayoutRes int layoutResId) {
        this.layoutResId = layoutResId;
    }

    @Override
    public void notifyDataChanged(List<T> ts, boolean b) {
        if (b) {
            mDatas = new ArrayList<>();
            mDatas.clear();
        }
        mDatas.addAll(ts);
        if (b) {
            notifyDataSetChangedHF();
        } else {
            notifyItemRangeChangedHF(mDatas.size() - ts.size(), ts.size());
        }
    }

    @Override
    public List<T> getData() {
        return mDatas;
    }

    public T getItem(int position) {
        if(position > mDatas.size()){
            return null;
        }
        return mDatas.get(position);
    }

    @Override
    public boolean isEmpty() {
        return mDatas.isEmpty();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolderHF(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutResId, viewGroup, false);
        return new RecyViewHolder(view);
    }

    @Override
    public void onBindViewHolderHF(RecyclerView.ViewHolder viewHolder, int i) {
        if (viewHolder instanceof RecyViewHolder) {
            convert((RecyViewHolder) viewHolder, mDatas.get(i));
        }
    }

    @Override
    public int getItemCountHF() {
        return mDatas.size();
    }

    protected abstract void convert(RecyViewHolder holder, T item);
}
